from flask import Blueprint, current_app, request,jsonify
import akshare as ak
import requests as rq
import pandas as pd
import datetime


sdata = Blueprint('sdata', __name__)
@sdata.route('/daily')
def stock_data_daily():
    stock_zh_a_hist_df = ak.stock_zh_a_hist(symbol="603679", period="daily", start_date="20210101", end_date="20211231",
                                            adjust="qfq")
    return {'code': 200, 'data': stock_zh_a_hist_df.to_json(orient='values')}

# 获取实时股票行情
@sdata.route('/narrow', methods=["GET", "POST"])
def stock_data_narrow():
    code = request.json['code']
    url = 'https://apphwhq.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockL2Data',
              'a': 'GetStockPanKou_Narrow', 'PhoneOSNew': '2',
              'VerSion': '5.16.0.5',
              'apiv': 'w37', 'State': 2}
    re = rq.post(url, params=params)
    result = re.json()

    # data_df = pd.DataFrame(columns=['close', 'open', 'high', 'low', 'timestamp','turnover','volume'])
    # if int(result['errcode']) == 0:
    #     day_data = list()
    #     day_data.append(result['real']['last_px'])
    #     day_data.append(result['real']['open_px'])
    #     day_data.append(result['real']['high_px'])
    #     day_data.append(result['real']['low_px'])
    #     date_str = result['real']['time']
    #     timestamp = int(datetime.datetime.strptime(date_str, '%Y%m%d').timestamp() * 1000)
    #     day_data.append(timestamp)
    #     day_data.append(result['real']['total_turnover'])
    #     day_data.append(result['real']['circulation_amount'])
    #     data_df.loc[0] = day_data
    #     return jsonify({'code': 1, 'data': data_df.to_dict(orient='records'), 'message': '请求成功'})
    if int(result['errcode']) == 0:
        return jsonify({'code': 1, 'data': result, 'message': '请求成功'})

    return jsonify({'code': 0, 'message': '请求失败'})

# 获取历史日线股票行情
@sdata.route('/stockLineData', methods=["GET", "POST"])
def get_stockLineData():

    code = request.json['code']
    index = 0
    if request.json.get('index'):
        index = int(request.json['index'])
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockLineData',
              'a': 'GetKLineDay_W14', 'PhoneOSNew': '2',
              'VerSion': '5.16.0.5',
              'apiv': 'w37', 'st': 240, 'Index': index,
              'Is_FS': 1}
    re = rq.post(url, params=params)
    result = re.json()
    data_df = pd.DataFrame(columns=['close', 'open', 'high', 'low', 'timestamp','turnover','volume'])
    if int(result['errcode']) == 0:
        for index, data in enumerate(result['turnover']):
            day_data = list()
            day_data.extend(result['y'][index])
            date_str = result['x'][index]
            timestamp = int(datetime.datetime.strptime(date_str, '%Y%m%d').timestamp() * 1000)
            day_data.append(timestamp)
            day_data.append(result['turnover'][index])
            day_data.append(result['vol'][index])
            data_df.loc[index] = day_data
        return jsonify({'code': 1, 'data': data_df.to_dict(orient='records'), 'message': '请求成功'})
    return jsonify({'code': 0, 'data': {}, 'message': '请求失败'})

# 获取历史日线股票行情(kpl)
@sdata.route('/kplStockLineData', methods=["GET", "POST"])
def get_kplStockLineData():

    code = request.json['code']
    index = 0
    if request.json.get('index'):
        index = int(request.json['index'])
    url = 'https://apphis.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockLineData',
              'a': 'GetKLineDay_W14', 'PhoneOSNew': '2',
              'VerSion': '5.16.0.5',
              'apiv': 'w37', 'st': 240, 'Index': index,
              'Is_FS': 1}
    re = rq.post(url, params=params)
    result = re.json()
    if int(result['errcode']) == 0:

        return jsonify({'code': 1, 'data': result, 'message': '请求成功'})
    return jsonify({'code': 0, 'data': {}, 'message': '请求失败'})


# 获取今日分时线行情
@sdata.route('/kplTrendIncremental', methods=["GET", "POST"])
def get_kplTrendIncremental():
    code = request.json['code']
    url = 'https://apphwhq.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockL2Data',
              'a': 'GetStockTrendIncremental', 'PhoneOSNew': '2',
              'VerSion': '5.16.0.5', 'apiv': 'w38'}
    # GetStockVolTurIncremental
    re = rq.post(url, params=params)
    result = re.json()
    # data_df = pd.DataFrame(columns=['close', 'open', 'high', 'low', 'timestamp', 'turnover', 'volume'])
    if int(result['errcode']) == 0:
        # for index, data in enumerate(result['trend']):
        #     print(data)
        #     day_data = list()
        #     day_data.append(data[2])
        #     day_data.append(data[2])
        #     day_data.append(data[2])
        #     day_data.append(data[2])
        #
        #     date_str = result['day'] + data[0]
        #     timestamp = int(datetime.datetime.strptime(date_str, '%Y%m%d%H:%M').timestamp() * 1000)
        #     day_data.append(timestamp)
        #     day_data.append(data[4])
        #     day_data.append(data[3])
        #     data_df.loc[index] = day_data
        return jsonify({'code': 1, 'data': result, 'message': '请求成功'})
    return jsonify({'code': 0, 'data': {}, 'message': '请求失败'})

#获取前几日分时线行情
@sdata.route('/kplStockTrend5Min', methods=["GET", "POST"])
def get_stockTrend5Min():
    code = request.json['code']
    url = 'https://apphwhq.longhuvip.com/w1/api/index.php'
    params = {'StockID': code, 'c': 'StockL2Data',
              'a': 'GetStockTrend5Min', 'PhoneOSNew': '2',
              'VerSion': '5.16.0.5', 'apiv': 'w38'}
    re = rq.post(url, params=params)
    result = re.json()
    # data_df = pd.DataFrame(columns=['close', 'open', 'high', 'low', 'timestamp', 'turnover', 'volume'])
    if int(result['errcode']) == 0:
        # index = 0
        # for trend in result['List']:
        #     for data in trend['trend']:
        #         day_data = list()
        #         day_data.append(data[2])
        #         day_data.append(data[2])
        #         day_data.append(data[2])
        #         day_data.append(data[2])
        #         date_str = trend['day'] + data[0]
        #         timestamp = int(datetime.datetime.strptime(date_str, '%Y-%m-%d%H:%M').timestamp() * 1000)
        #         day_data.append(timestamp)
        #         day_data.append(data[5])
        #         day_data.append(data[3])
        #         data_df.loc[index] = day_data
        #         index += 1
        return jsonify({'code': 1, 'data': result, 'message': '请求成功'})
    return jsonify({'code': 0, 'data': {}, 'message': '请求失败'})
